package cn.com.callback

import cn.com.kh.KHUtil
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.EliteBean;
import cn.com.elite.Util
import org.json.JSONException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.com.kh.getProperty;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import java.time.Instant;

/**
 *
 * @Title: aipHSTstatisfaction
 * @Description:华盛证券  获取明元侧满意度结果 --内部接口
 * @author: chieh
 * @date 2023-05-29 10:28:00
 *
 */

public class aipHSTstatisfaction implements ServiceBackInvoke {
	private static final Log log = LogFactory.getLog(aipHSTstatisfaction.class);
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();

		log.debug("getMethod:" + getMethod);
		long endTime ;
		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}
		log.debug("-------------------------start aipHSTstatisfaction 获取满意度开始-----------------");

		try {
			String uui="";
			String SKILL_DESC="";

			//查询 待捞取的任务
			List selectList = eliteBean.chaxun_sql("select ws.SKILL_DESC as SKILL_DESC,r.initcallid as uui from  WMSK_Statisfaction ws LEFT JOIN record r on ws.event_guid=r.event_guid and ws.STAFF_ID=r.STAFF_ID where 1=1 and ws.STATISFACTION1 is null and ifnull(ws.YES_OR_ISSUE,0)<3 and r.STARTTIME>=NOW()-INTERVAL 1 day order by ws.YES_OR_ISSUE,r.STARTTIME asc limit 100", "dataSource");
			def count = selectList.size();
			log.debug("待处理的满意度数量 count：" + count);
			//判断如待处理的数据数量大于0则执行
			if(count> 0){
				for(int i = 0; i<count; i++) {
					Map selectdMap = selectList.get(i);
					uui = selectdMap.get("uui");//唯一id
					SKILL_DESC = selectdMap.get("SKILL_DESC");//uui ATTACHEDDATA 1685350789.36
					log.debug("uui:" + uui+"	,SKILL_DESC:" + SKILL_DESC);//
					try {
						outData = searchapi(eliteBean, SKILL_DESC,uui,dataSourceID);
					}catch (Exception e) {
						log.error("解析异常:" + e.getMessage());
					}
				}
			}

			outData = "{\"resultcode\":\"1\",\"resultmessage\":\"处理成功\"}";
		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
		}

		log.debug("更新chat_request表 信息完成返回结果:" + outData);

		return outData;
	}

	//searchapi
	public static String searchapi(EliteBean eliteBean , String SKILL_DESC ,String uui , String dataSourceID) {

		long startTime = System.currentTimeMillis();
		log.debug("处理开始时间:" + startTime);

		long endTime = System.currentTimeMillis();

		String reJson = null;
		try {

			//http://192.168.90.21:9210
			String doURL = getProperty.get("MYURL");
			doURL = doURL+"/api/pbx/cdr/main?method=search";
			log.debug("doURL:" + doURL);

			Map<String, String> headMap = new HashMap<String, String>();
			headMap.put("Content-Type", "application/json");
			headMap.put("method", "search");


			def injson="{\n" +
					"    \"request\": {\n" +
					"        \"column\": [\n" +
					"            \"id\",\n" +
					"            \"accountcode\",\n" +
					"            \"uniqueid\",\n" +
					"            \"calldate\",\n" +
					"            \"calltype\",\n" +
					"            \"billtype\",\n" +
					"            \"did\",\n" +
					"            \"cnam\",\n" +
					"            \"cnum\",\n" +
					"            \"dnam\",\n" +
					"            \"dnum\",\n" +
					"            \"src\",\n" +
					"            \"dst\",\n" +
					"            \"channel\",\n" +
					"            \"dstchannel\",\n" +
					"            \"trunk\",\n" +
					"            \"prefix\",\n" +
					"            \"callerid\",\n" +
					"            \"hanguper\",\n" +
					"            \"device\",\n" +
					"            \"devicename\",\n" +
					"            \"dstdevice\",\n" +
					"            \"dstdevicename\",\n" +
					"            \"member\",\n" +
					"            \"dstmember\",\n" +
					"            \"devicemerge\",\n" +
					"            \"devicenamemerge\",\n" +
					"            \"membermerge\",\n" +
					"            \"location\",\n" +
					"            \"duration\",\n" +
					"            \"billsec\",\n" +
					"            \"talksec\",\n" +
					"            \"disposition\",\n" +
					"            \"ownerid\",\n" +
					"            \"score\",\n" +
					"            \"recordingfile\"\n" +
					"        ],\n" +
					"        \"where\": {\n" +
					"            \"AND\": {\n" +
					"                \"uniqueid\": \"" +uui +"\"\n"+
					"            },\n" +
					"            \"LIMIT\": 1,\n" +
					"            \"ORDER\": {\n" +
					"                \"id\": \"DESC\"\n" +
					"            }\n" +
					"        }\n" +
					"    }\n" +
					"}";


			log.debug("injson:" + injson);

			def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
			log.debug("getResult:" + getResult);

			//解析接口返回信息
			org.json.JSONObject jsonObject = new org.json.JSONObject(getResult);
			String code = GetJV(jsonObject, "code");
			String datajson = GetJV(jsonObject, "data");

			org.json.JSONObject dataObject;
			org.json.JSONArray itemsarray;
			org.json.JSONObject scoreObject;

			log.debug("code:" + code);
			if(code == "200") {
				dataObject = new org.json.JSONObject(datajson);
				log.debug("dataObject:" + dataObject);
				String items = GetJV(dataObject, "items");
				itemsarray  = new org.json.JSONArray(items);
				String scorejson= itemsarray.getJSONObject(0);
				scoreObject = new org.json.JSONObject(scorejson);
				String score = GetJV(scoreObject, "score");

				String[] data1=new String[1];
				if(itemsarray.length()>0&&score!='') {
					data1[0] = "update wmsk_statisfaction set STATISFACTION1='"+score+"',YES_OR_ISSUE=IFNULL(YES_OR_ISSUE,0)+1,MODIFIEDDATE=now()  where SKILL_DESC='"+SKILL_DESC+"'";
					log.debug("当前获取的满意度结果更新SQL:" + data1.toString());
				}else {
					data1[0] = "update wmsk_statisfaction set YES_OR_ISSUE=IFNULL(YES_OR_ISSUE,0)+1,MODIFIEDDATE=now()  where SKILL_DESC='"+SKILL_DESC+"'";
					log.debug("当前获取的满意度结果失败更新SQL:" + data1.toString());
				}
				int[] dataresult1 = eliteBean.updateBatch(data1, "dataSource");
				log.debug("当前获取的满意度结果更新SQL结果:" + dataresult1.toString());

				//返回认证信息成功
				reJson = "{\"result\":\"1\",\"message\":\"满意度获取成功\",\"password\":\"\"}";
			}else {
				String msg = GetJV(jsonObject, "msg");
				reJson = "{\"result\":\"-1\",\"message\":\"满意度获取失败(" + msg + ")\"}";
			}

		} catch (JSONException e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			reJson = "{\"result\":\"-1\",\"message\":\"满意度获取异常\"}";
		}

		return reJson;
	}


	// 解析Json值
	public static String GetJV(org.json.JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		log.debug("解析-k=" + getKey + " v=" + Rev_Value);
		return Rev_Value;
	}


	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}
